/**
 * 
 */
package com.df.tv.launcher.view;

import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import com.df.tv.launcher.R;

import com.df.tv.launcher.entity.PlayInfo;
import com.df.tv.launcher.util.JsonParseUtil;
import com.df.tv.launcher.util.XHttpParamsUtil;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.telecom.tv189.comlib.dynamicui.DynamicView;
import com.telecom.tv189.comlib.dynamicui.json.ActionPerformer;
import com.telecom.tv189.comlib.dynamicui.json.ActionPerformer.PerformException;
import com.telecom.tv189.comlib.dynamicui.view.FrameLayout;
import com.telecom.tv189.comlib.models.ClickLogSender;
import com.telecom.tv189.comlib.net.XHttpClient;
import com.telecom.tv189.comlib.net.json.entity.BaseEntity;
import com.telecom.tv189.comlib.util.Attributes;
import com.telecom.tv189.comlib.util.BitmapHelp;
import com.telecom.tv189.comlib.util.Log;
import com.telecom.tv189.silentlogin.UserInfo;
import com.telecom.tv189.silentlogin.UserInfoKeeper;

/**
 * 视频直接在View上播放
 * 
 * @author lcw 2014-4-24 下午2:59:14
 */
public class VideoPlayerView extends RelativeLayout implements DynamicView {
    private static final String TAG = "VideoPlayerView";
    // xxhuang add
    // for auto gen
    public static final String CLASS_PATTERN = "VideoPlayerView";

    public static final String ATTR_COVER_IMG_SRC = "coverImgSrc";
    public static final String ATTR_VIDEO_SRC = "videoSrc";
    public static final String ATTR_VIDEO_CONTETN_ID = "videoid";

    private SurfaceView surfaceView;
    private ImageView playing_imgV;
    private ProgressBar video_progress; // progress为播放进度，secendProgress为缓冲进度

    private MediaPlayer mediaPlayer;
    // private int mSurfaceContainWidth=200,mSurfaceContainHeight=200;
    //	private VIDEOSIZESTATE						mVideoSizeState			= VIDEOSIZESTATE.ORIGINAL;
    //	private boolean								mIsLandscape			= true;

    private String videoPlayURL = null; // 当前视频播放地址
    private String videoDataURL = null; // 服务器下发的视频播放地址
    private String videoContentId = null; // 视频Contentid
    private ScheduledExecutorService excuter;

    private MediPlayerState mediaPlayerState = MediPlayerState.NULL;

    private ImageView play_progress_imgv;

    private ImageView playing_bg_imgV;
    Handler handle = null;
    /** 是否在数据解析创建完成后 自动开始播放 */
    private boolean auToStartPlay = false;

    private static ArrayList<VideoPlayerView> instanceTags = new ArrayList<VideoPlayerView>();

    public enum MediPlayerState {
    NULL, Idle, Initialized, Preparing, Prepared, Started, Paused, Stoped, PlayBackCompleted
    }

    /** 视频显示大小状态 */
    //	private static enum VIDEOSIZESTATE {
    //	ORIGINAL, FOUR_RATIO_THREE, SIXTEEN_RATIO_NINE, FULL;
    //	}

    /**
     * @param context
     */
    public VideoPlayerView(Context context) {
        super(context);
        handlerThread.start();
        handle = new MyHandle(handlerThread.getLooper());
        // init(context);
    }

    /**
     * @param context
     * @param attrs
     * @param defStyle
     */
    public VideoPlayerView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        handlerThread.start();
        handle = new MyHandle(handlerThread.getLooper());
        // init(context);
    }

    /**
     * @param context
     * @param attrs
     */
    public VideoPlayerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        handlerThread.start();
        handle = new MyHandle(handlerThread.getLooper());

        // init(context);
    }

    private void init(final Context context) {
        setClickable(true);
        setFocusable(true);
        setFocusableInTouchMode(true);
        setGravity(android.view.Gravity.CENTER);
        setBackgroundResource(R.drawable.preview_1_background);

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View mPreview = inflater.inflate(R.layout.video_player_view, this, false);
        addView(mPreview, new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

        surfaceView = (SurfaceView) mPreview.findViewById(R.id.vidoe_surfaceView);
        // surfaceView.setZOrderMediaOverlay(true);
        // surfaceView.setZOrderOnTop(true);

        playing_imgV = (ImageView) mPreview.findViewById(R.id.playing_imgV);
        video_progress = (ProgressBar) mPreview.findViewById(R.id.video_progress);
        play_progress_imgv = (ImageView) mPreview.findViewById(R.id.play_progress_imgv);
        playing_bg_imgV = (ImageView) mPreview.findViewById(R.id.playing_bg_imgV);

        handle.sendEmptyMessage(HandleAction.RESET);

        surfaceView.getHolder().addCallback(new Callback() {

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {

            }

            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                Log.d(TAG, "surfaceView.surfaceCreated(),mediaPlayer=" + (mediaPlayer == null ? "null" : mediaPlayer));
                if (mediaPlayer != null) {
                    mediaPlayer.setDisplay(holder);
                    Log.d(TAG, "surfaceView.surfaceCreated(),mediaPlayer.setDisplay(holder)");
                }

                if (auToStartPlay)
                    mPlay();

            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                Log.d(TAG, "surfaceView.getHolder().surfaceChanged(" + width + "," + height + ")");
            }
        });
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.view.View#onVisibilityChanged(android.view.View, int)
     */
    @Override
    protected void onVisibilityChanged(View changedView, int visibility) {
        super.onVisibilityChanged(changedView, visibility);
        if (visibility == View.INVISIBLE && isPlaying()) {
            mPause(true);
            Log.d(TAG, "onVisibilityChanged(View.INVISIBLE),mPause()");
        }
        else if (visibility == View.VISIBLE && mediaPlayerState == MediPlayerState.Paused) {
            Log.d(TAG, "onVisibilityChanged(View.VISIBLE),mPlay()");
            mPlay();
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.view.ViewGroup#onAttachedToWindow()
     */
    @Override
    protected void onAttachedToWindow() {
        Log.d(TAG, "onAttachedToWindow");
        super.onAttachedToWindow();
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.view.ViewGroup#onDetachedFromWindow()
     */
    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        Log.d(TAG, "onDetachedFromWindow");
    }

    /**
     * @param videoCoverImgURL
     *            the videoCoverImgURL to set
     */
    public void setVideoCoverImgURL(String videoCoverImgURL) {
        if (playing_bg_imgV != null && !TextUtils.isEmpty(videoCoverImgURL)) {
            BitmapHelp.getBitmapUtils(getContext()).display(playing_bg_imgV, videoCoverImgURL,
                    BitmapHelp.getBitmapDisplayConfig());
        }
    }

    /**
     * 设置播放地址，如果为空，则使用下发 videoDataURL
     * 
     * @param url
     */
    public void setVideoPlayURL(String url) {
        if (TextUtils.isEmpty(url)) {
            videoPlayURL = videoDataURL;
        }
        else
            videoPlayURL = url;

        Log.d(TAG, "videPlayURL=" + videoPlayURL);
    }

    public String getVideoPlayURL() {
        return videoPlayURL;
    }

    private void setLoop(boolean looping) {
        if (mediaPlayer != null) {
            mediaPlayer.setLooping(looping);
        }
    }

    public boolean isPlaying() {
        if (mediaPlayer != null) {
            try {
                return mediaPlayer.isPlaying();
            } catch (Exception e) {
                return false;
            }
        }
        return false;
    }

    private void initialMediaPlay() {
        if (mediaPlayer == null) {
            Log.d(TAG, "initialMediaPlay " + mediaPlayerState);
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setOnPreparedListener(new OnPreparedListener() {

                @Override
                public void onPrepared(MediaPlayer mp) {
                    mediaPlayerState = MediPlayerState.Prepared;
                    Log.d(TAG, "prepare completed current state=" + mediaPlayerState);
                    mPlay();
                }
            });

            // 缓冲进度
            mediaPlayer.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {

                @Override
                public void onBufferingUpdate(MediaPlayer mp, int percent) {
                    if (percent > 0)
                        video_progress.setSecondaryProgress(percent);
                }
            });

            mediaPlayer.setOnErrorListener(new OnErrorListener() {

                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    StringBuffer str = new StringBuffer();
                    switch (what) {
                    case MediaPlayer.MEDIA_ERROR_IO:// File or network related
                                                    // operation errors.
                        str.append("MediaPlayer.MEDIA_ERROR_IO");
                        break;
                    case MediaPlayer.MEDIA_ERROR_MALFORMED:
                        str.append("MediaPlayer=MEDIA_ERROR_MALFORMED");
                        break;
                    case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
                        str.append("MediaPlayer=MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK");
                        break;
                    case MediaPlayer.MEDIA_ERROR_TIMED_OUT:
                        str.append("MediaPlayer=MEDIA_ERROR_TIMED_OUT");
                        break;
                    case MediaPlayer.MEDIA_ERROR_UNSUPPORTED:
                        str.append("MediaPlayer=MEDIA_ERROR_UNSUPPORTED");
                        break;
                    case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
                        str.append("MediaPlayer=MEDIA_ERROR_SERVER_DIED");
                        break;
                    case MediaPlayer.MEDIA_ERROR_UNKNOWN:
                        str.append("MediaPlayer=MEDIA_ERROR_UNKNOWN");
                        break;
                    default:
                        str.append("MediaPlayer=other:" + extra);
                        break;
                    }

                    switch (extra) {
                    case MediaPlayer.MEDIA_ERROR_IO:// File or network related
                                                    // operation errors.
                        str.append(",extra=MEDIA_ERROR_IO");
                        break;
                    case MediaPlayer.MEDIA_ERROR_MALFORMED:
                        str.append(",extra=MEDIA_ERROR_MALFORMED");
                        break;
                    case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
                        str.append(",extra=MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK");
                        break;
                    case MediaPlayer.MEDIA_ERROR_TIMED_OUT:
                        str.append(",extra=MEDIA_ERROR_TIMED_OUT");
                        break;
                    case MediaPlayer.MEDIA_ERROR_UNSUPPORTED:
                        str.append(",extra=MEDIA_ERROR_UNSUPPORTED");
                        break;
                    case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
                        str.append(",extra=MEDIA_ERROR_SERVER_DIED");
                        break;
                    case MediaPlayer.MEDIA_ERROR_UNKNOWN:
                        str.append(",extra=MEDIA_ERROR_UNKNOWN");
                        break;

                    default:
                        str.append(",extra=other:" + extra);
                        break;
                    }

                    Log.d(TAG, str.toString());

                    handle.removeMessages(HandleAction.STOP);
                    handle.sendEmptyMessage(HandleAction.STOP);

                    handle.removeMessages(HandleAction.RESET);
                    handle.sendEmptyMessage(HandleAction.RESET);
                    return true;
                }
            });

            mediaPlayer.setOnVideoSizeChangedListener(new OnVideoSizeChangedListener() {

                @Override
                public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
                    Log.d(TAG, "mediaPlayer.setOnVideoSizeChangedListener(" + mediaPlayer.getVideoWidth() + ","
                            + mediaPlayer.getVideoHeight() + ")");
                    //					handle.removeMessages(HandleAction.CHANGE_SURFACE_HOLDER_SIEZ);
                    //					handle.sendEmptyMessageDelayed(HandleAction.CHANGE_SURFACE_HOLDER_SIEZ, 100);
                }
            });
            mediaPlayer.setOnCompletionListener(new OnCompletionListener() {

                @Override
                public void onCompletion(MediaPlayer mp) {
                    mediaPlayerState = MediPlayerState.PlayBackCompleted;
                    if (mediaPlayer.isLooping()) {
                        mPlay();
                    }
                }
            });
            if (surfaceView != null && surfaceView.getHolder() != null && surfaceView.getHolder().getSurface() != null
                    && surfaceView.getHolder().getSurface().isValid()) {
                try {
                    mediaPlayer.setDisplay(surfaceView.getHolder());
                } catch (Exception e) {//maybe throw java.lang.IllegalArgumentException: The surface has been released
                    Log.d(TAG, e.getMessage());
                }
            }
        }
        else {
            mediaPlayer.reset();// 重置为初始状态
        }
        mediaPlayerState = MediPlayerState.Idle;
    }

    private void initial() {
        try {
            if (mediaPlayerState == MediPlayerState.Idle) {
                if (TextUtils.isEmpty(videoPlayURL)) {
                    Log.d(TAG, "videoPlayURL is emtpty,not do prepare current state=" + mediaPlayerState);
                    return;
                }

                Log.d(TAG, "do inital current state=" + mediaPlayerState);
                mediaPlayer.setDataSource(videoPlayURL);
                // call befor prepare()
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mediaPlayer.setScreenOnWhilePlaying(true);
                mediaPlayerState = MediPlayerState.Initialized;
                setLoop(true);
                handle.removeMessages(HandleAction.PREPARE);
                handle.sendEmptyMessageDelayed(HandleAction.PREPARE, 300);
            }

        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void prepare() {
        if (mediaPlayerState == MediPlayerState.Initialized || mediaPlayerState == MediPlayerState.Stoped) {
            mediaPlayerState = MediPlayerState.Preparing;
            Log.d(TAG, "prepare start current state=" + mediaPlayerState);
            mediaPlayer.prepareAsync();// 缓冲
        }
        else if (mediaPlayerState == MediPlayerState.Idle) {
            handle.removeMessages(HandleAction.INITIAL);
            handle.sendEmptyMessageDelayed(HandleAction.INITIAL, 300);
        }
    }

    private void mPlay() {
        handle.removeMessages(HandleAction.RESET);
        handle.removeMessages(HandleAction.PLAY);
        handle.removeMessages(HandleAction.PAUSE);
        handle.removeMessages(HandleAction.STOP);
        handle.removeMessages(HandleAction.RELEASE);

        Log.d(TAG, "play() current state=" + mediaPlayerState);
        if (mediaPlayerState == MediPlayerState.Prepared || mediaPlayerState == MediPlayerState.Paused
                || mediaPlayerState == MediPlayerState.PlayBackCompleted) {
            //			handle.removeMessages(HandleAction.PLAY);
            handle.sendEmptyMessageDelayed(HandleAction.PLAY, 500);
        }
        else if (mediaPlayerState == MediPlayerState.Initialized || mediaPlayerState == MediPlayerState.Stoped) {
            handle.removeMessages(HandleAction.PREPARE);
            handle.sendEmptyMessageDelayed(HandleAction.PREPARE, 300);
        }
        else if (mediaPlayerState == MediPlayerState.Idle) {
            handle.removeMessages(HandleAction.INITIAL);
            handle.sendEmptyMessageDelayed(HandleAction.INITIAL, 300);
        }
        else if (mediaPlayerState == MediPlayerState.NULL) {
            handle.sendEmptyMessage(HandleAction.RESET);
            handle.removeMessages(HandleAction.INITIAL);
            handle.sendEmptyMessageDelayed(HandleAction.INITIAL, 300);
        }
    }

    private void mPause(boolean showVideoCover) {
        handle.removeMessages(HandleAction.PLAY);
        handle.removeMessages(HandleAction.PAUSE);
        handle.sendEmptyMessageDelayed(HandleAction.PAUSE, 300);
        showVideoBg(showVideoCover);
    }

    private void mStop() {
        handle.removeMessages(HandleAction.STOP);
        handle.sendEmptyMessageDelayed(HandleAction.STOP, 300);
    }

    /**
     * should be call ,when view destroy
     */
    private void mRelase() {
        handle.removeMessages(HandleAction.RELEASE);
        handle.sendEmptyMessageDelayed(HandleAction.RELEASE, 300);
    }

    public void play() {
        Log.d(TAG, "out side play()");
        mPlay();
    }

    public void pause(boolean showVideoCover) {
        Log.d(TAG, "out side pause(" + showVideoCover + ")");
        mPause(showVideoCover);
    }

    public void stop() {
        Log.d(TAG, "out side stop()");
        mStop();
    }

    /**
     * should be call ,when view destroy
     */
    public void relase() {
        Log.d(TAG, "out side relase()");
        mRelase();
    }

    /**
     * 根据mVideoSizeState来计算出video宽高
     */
    //	private void calculateVideoWH() {
    //		int videoW=0;
    //		int videoH =0;
    //		try{
    //		  videoW = mediaPlayer.getVideoWidth();
    //		  videoH = mediaPlayer.getVideoHeight();
    //		}catch (Exception e) {
    //			e.printStackTrace();
    //			return;
    //		}
    //		int mSurfaceContainWidth = (int) (VideoPlayerView.this.getWidth() * VideoPlayerView.this.getScaleX());
    //		int mSurfaceContainHeight = (int) (VideoPlayerView.this.getHeight() * VideoPlayerView.this.getScaleY());
    //
    //		int mVideoWidth = 0, mVideoHeight = 0;
    //		if (mIsLandscape) {// view W > H
    //			switch (mVideoSizeState) {
    //			case ORIGINAL:
    //				if(videoW<=0 || videoH<=0 ||mSurfaceContainWidth<=0 || mSurfaceContainHeight<=0){
    //					return;
    //				}
    //				
    //				float surfaceContainScale = ((float) mSurfaceContainWidth) / mSurfaceContainHeight;
    //				float videoScale = ((float) videoW) / videoH;
    //
    //				Log.d(TAG, "surfaceContainScale = " + surfaceContainScale + ",videoScale=" + videoScale);
    //				if (surfaceContainScale > videoScale) {
    //					// 撑满高，来计算宽
    //					mVideoHeight = mSurfaceContainHeight;
    //					mVideoWidth = (int) (videoScale * mVideoHeight);
    //				}
    //				else {
    //					// 撑满宽，来计算高
    //					mVideoWidth = mSurfaceContainWidth;
    //					mVideoHeight = (int) (mVideoWidth / videoScale);
    //				}
    //
    //				// if (surfaceContainScale > videoScale) {
    //				// // 撑满高，来计算宽
    //				// mVideoHeight = mSurfaceContainHeight;
    //				// mVideoWidth = (int) (videoScale * mVideoHeight);
    //				// } else {
    //				// // 撑满宽，来计算高
    //				// mVideoWidth = mSurfaceContainWidth;
    //				// mVideoHeight = (int) (mVideoWidth / videoScale);
    //				// }
    //				break;
    //			case FOUR_RATIO_THREE:
    //				// mVideoHeight = mVideoOriginalHeight > mSurfaceContainHeight ?
    //				// mSurfaceContainHeight : mVideoOriginalHeight;
    //				mVideoHeight = mSurfaceContainHeight - mSurfaceContainHeight / 5;
    //				mVideoWidth = mVideoHeight * 4 / 3;
    //				break;
    //			case SIXTEEN_RATIO_NINE:
    //				// mVideoHeight = mVideoOriginalHeight > mSurfaceContainHeight ?
    //				// mSurfaceContainHeight : mVideoOriginalHeight;
    //				mVideoHeight = mSurfaceContainHeight - mSurfaceContainHeight / 5;
    //				mVideoWidth = mVideoHeight * 16 / 9;
    //				break;
    //			case FULL:
    //				mVideoHeight = mSurfaceContainHeight;
    //				mVideoWidth = mSurfaceContainWidth;
    //				break;
    //			}
    //		}
    //		else {
    //			mVideoHeight = mSurfaceContainHeight;
    //			mVideoWidth = mSurfaceContainWidth;
    //		}
    //
    //		setVideoSize(mVideoWidth, mVideoHeight);
    //
    //		Log.d(TAG, "mVideoWidth = " + mVideoWidth + ",mVideoHeight = " + mVideoHeight);
    //	}
    //
    //	private void setVideoSize(int width, int height) {
    //		surfaceView.getHolder().setFixedSize(width, height);
    //	}

    /**
     * 更新VideoPlayer的大小，根据View大小
     */
    public void changeVideoSize(boolean scale) {
        Log.d(TAG, "changeVideoSize(scale:" + scale + ")");
        uiHandle.removeMessages(HandleAction.CHANGE_SURFACE_SIZE);
        uiHandle.sendEmptyMessageDelayed(HandleAction.CHANGE_SURFACE_SIZE, 100);
    }

    private void changeSurfaceSize() {
        //		if (mediaPlayer!=null  
        //			&&(mediaPlayerState == MediPlayerState.Started
        //				||mediaPlayerState == MediPlayerState.Prepared
        //				||mediaPlayerState == MediPlayerState.Paused
        //			 )
        //		){
        int w = (int) (VideoPlayerView.this.getWidth() * VideoPlayerView.this.getScaleX());
        int h = (int) (VideoPlayerView.this.getHeight() * VideoPlayerView.this.getScaleY());
        Log.d(TAG, "changeSurfaceSize() W=" + w + ",new H=" + h);
        surfaceView.setLayoutParams(new FrameLayout.LayoutParams(w, h));

        //			handle.removeMessages(HandleAction.CHANGE_SURFACE_HOLDER_SIEZ);
        //			handle.sendEmptyMessageDelayed(HandleAction.CHANGE_SURFACE_HOLDER_SIEZ, 100);
        //		}
    }

    private interface HandleAction {
        int RESET = 0, INITIAL = 1, PREPARE = 2, PLAY = 3, PAUSE = 4, STOP = 5, RELEASE = 6, UPDATE_PLAY_PROGRESS = 7,
                REQUEST_FOCUSE = 8
                // ,HIDE_COVER_IMG=9
                //				, CHANGE_SURFACE_HOLDER_SIEZ = 10
                , CHANGE_SURFACE_SIZE = 11;
    }

    HandlerThread handlerThread = new HandlerThread("handler_thread");
    private Handler uiHandle = new Handler() {
        /*
         * (non-Javadoc)
         * 
         * @see
         * android.os.Handler#handleMessage(
         * android.os.Message)
         */
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case HandleAction.PLAY:
                if (mediaPlayerState == MediPlayerState.Started) {
                    if (playing_imgV.getVisibility() != View.GONE)
                        playing_imgV.setVisibility(View.GONE);
                    if (playing_bg_imgV.getVisibility() != View.GONE)
                        playing_bg_imgV.setVisibility(View.GONE);
                }
                else {
                    if (playing_imgV.getVisibility() != View.VISIBLE)
                        playing_imgV.setVisibility(View.VISIBLE);
                    if (playing_bg_imgV.getVisibility() != View.VISIBLE)
                        playing_bg_imgV.setVisibility(View.VISIBLE);
                }
                break;
            case HandleAction.UPDATE_PLAY_PROGRESS:
                int currentPro = 0;
                int duration = 0;
                try {
                    currentPro = mediaPlayer.getCurrentPosition();
                    duration = mediaPlayer.getDuration();
                } catch (IllegalStateException e) {} catch (NullPointerException e) {}
                if (duration > 0) {
                    float percent = currentPro * 1.0f / duration;
                    updatePlayedIndcator(percent);
                }
                break;
            case HandleAction.REQUEST_FOCUSE:
                VideoPlayerView.this.requestFocus();
                break;
            case HandleAction.CHANGE_SURFACE_SIZE:
                changeSurfaceSize();
                break;
            }
        }
    };

    class MyHandle extends Handler {

        public MyHandle() {
            super();
        }

        public MyHandle(Looper looper) {
            super(looper);
        }

        /*
         * (non-Javadoc)
         * 
         * @see android.os.Handler#handleMessage(android.os.Message)
         */
        @Override
        public void handleMessage(Message msg) {
            try {
                switch (msg.what) {
                case HandleAction.RESET:// 调用次功能前应先设置videoPlayURL的值
                    Log.d(TAG, "do Reset current state=" + mediaPlayerState);
                    uiHandle.sendEmptyMessage(HandleAction.PLAY);
                    initialMediaPlay();
                    Log.d(TAG, "initialMediaPlay done" + mediaPlayerState);
                    break;
                case HandleAction.INITIAL:// 调用次功能前应先设置videoPlayURL的值
                    Log.d(TAG, "inital current state=" + mediaPlayerState);
                    initial();
                    break;
                case HandleAction.PREPARE:// 调用次功能前应先设置videoPlayURL的值
                    Log.d(TAG, "prepare current state=" + mediaPlayerState);
                    prepare();
                    break;
                case HandleAction.PLAY:
                    if (mediaPlayer != null && !mediaPlayer.isPlaying()) {
                        Log.d(TAG, "PLAY current state=" + mediaPlayerState);
                        mediaPlayer.start();
                        mediaPlayerState = MediPlayerState.Started;
                        uiHandle.sendEmptyMessage(HandleAction.PLAY);
                        startProgressUpdateThread();
                    }
                    break;
                case HandleAction.PAUSE:
                    if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                        Log.d(TAG, "pause current state=" + mediaPlayerState);
                        mediaPlayerState = MediPlayerState.Paused;
                        uiHandle.sendEmptyMessage(HandleAction.PLAY);
                        mediaPlayer.pause();
                    }

                    break;
                case HandleAction.STOP:
                    if (mediaPlayer != null
                            && (mediaPlayerState == MediPlayerState.Prepared
                                    || mediaPlayerState == MediPlayerState.Started
                                    || mediaPlayerState == MediPlayerState.Paused || mediaPlayerState == MediPlayerState.PlayBackCompleted)) {
                        Log.d(TAG, "stop current state=" + mediaPlayerState);
                        mediaPlayer.stop();
                        mediaPlayerState = MediPlayerState.Stoped;
                        uiHandle.sendEmptyMessage(HandleAction.PLAY);
                        stopProgressUpdateThread();
                    }
                    break;
                case HandleAction.RELEASE:
                    Log.d(TAG, "release current state=" + mediaPlayerState);
                    mediaPlayer.release();
                    mediaPlayerState = MediPlayerState.NULL;
                    uiHandle.sendEmptyMessage(HandleAction.PLAY);
                    mediaPlayer = null; //next time use ,should be re create a new obj.
                    break;
                //				case HandleAction.CHANGE_SURFACE_HOLDER_SIEZ:
                //					calculateVideoWH();
                //					break;
                default:
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
                handle.removeMessages(HandleAction.RESET);
                handle.sendEmptyMessageDelayed(HandleAction.RESET, 300);
            }
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * com.telecom.tv189.comlib.dynamicui.DynamicView#applyAttributeSet(com.
     * telecom.tv189.comlib.dynamicui.Attributes, int)
     */
    @Override
    public void applyAttributeSet(Attributes attrs, int defStyle) {
        removeAllViews();

        instanceTags.add(this);
        setDrawingCacheEnabled(true);

        setVideoContentId(attrs.getString(ATTR_VIDEO_CONTETN_ID));
        videoDataURL = attrs.getString(ATTR_VIDEO_SRC);
        getVideoPlayUrlAndPlay();
        init(getContext());
        setVideoCoverImgURL(attrs.getString(ATTR_COVER_IMG_SRC));

        setTag(attrs);

        final ActionPerformer performer = attrs.get(ActionPerformer.KEY_ACTION, ActionPerformer.class);
        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    performer.invoke(v.getContext());
                } catch (PerformException e) {
                    e.printStackTrace();
                } catch (NullPointerException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    ClickLogSender.getInstance(getContext()).sendLog(v, performer.getArguments().getLogtag());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void startProgressUpdateThread() {
        if (excuter == null) {
            // 播放进度更新 Thread
            excuter = Executors.newSingleThreadScheduledExecutor();
            excuter.scheduleAtFixedRate(new Runnable() {
                public void run() {
                    uiHandle.sendEmptyMessage(HandleAction.UPDATE_PLAY_PROGRESS);
                }
            }, 1, 1, TimeUnit.SECONDS);
        }
    }

    private void stopProgressUpdateThread() {
        if (excuter != null) {
            excuter.shutdownNow();
            excuter = null;
        }
    }

    private void updatePlayedIndcator(float percent) {
        if (percent >= 0 && percent <= 1) {
            int rightP = (int) (percent * (video_progress.getWidth() - 10)) + 10 + 8;
            int pX = rightP - play_progress_imgv.getMeasuredWidth();
            play_progress_imgv.setX(pX);
        }
    }

    /**
     * return the all instance of this view
     * 
     * @return instanceTags
     */
    public static ArrayList<VideoPlayerView> getInstanceTags() {
        return instanceTags;
    }

    /**
     * @return the mediaPlayerState
     */
    public MediPlayerState getMediaPlayerState() {
        return mediaPlayerState;
    }

    private void showVideoBg(boolean show) {
        if (show) {
            playing_bg_imgV.setVisibility(View.VISIBLE);
        }
        else {
            playing_bg_imgV.setVisibility(View.GONE);
        }
    }

    /**
     * @see #videoContentId
     * @return the videoContentId
     */
    public String getVideoContentId() {
        return videoContentId;
    }

    /**
     * @see #videoContentId
     * @param videoContentId
     *            the videoContentId to set
     */
    public void setVideoContentId(String videoContentId) {
        this.videoContentId = videoContentId;
    }

    /** get video play url by contentid and auto play */
    private void getVideoPlayUrlAndPlay() {
        UserInfo userInfo = UserInfoKeeper.getInstance().getInfo();
        if (userInfo == null || TextUtils.isEmpty(userInfo.getToken()) || TextUtils.isEmpty(videoContentId)) {
            setVideoPlayURL(null);
            Log.d(TAG, "getVideoPlayUrlAndPlay(),userInfo = " + (userInfo == null ? "null" : userInfo));
            Log.d(TAG,
                    "getVideoPlayUrlAndPlay(),token = "
                            + (userInfo == null ? "userInfo = null" : (userInfo.getToken() == null ? "null" : userInfo
                                    .getToken())));
            Log.d(TAG, "getVideoPlayUrlAndPlay(),videoContentId = "
                    + (videoContentId == null ? "null" : videoContentId));
        }
        else {
            videoPlayURL = null;

            XHttpClient client = XHttpClient.getInstance();
            XHttpParamsUtil paramsUtil = XHttpParamsUtil.getInstance();
            client.get(paramsUtil.playInfo(userInfo.getToken(), videoContentId), new RequestCallBack<String>() {

                @Override
                public void onSuccess(ResponseInfo<String> arg0) {
                    String playUrl = null;
                    try {
                        BaseEntity<PlayInfo> playInfoEntity = JsonParseUtil.getInstance().getPlayInfo(arg0.result);
                        if (playInfoEntity.getCode() == 0) {
                            PlayInfo playInfo = playInfoEntity.getInfo();
                            playUrl = playInfo.getVideos().get(0).getPlayUrl();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    setVideoPlayURL(playUrl);

                    if (auToStartPlay)
                        mPlay();
                }

                @Override
                public void onFailure(HttpException arg0, String arg1) {
                    setVideoPlayURL(null);
                    if (auToStartPlay)
                        mPlay();
                }
            });
        }
    }
}
